<template>
  <!-- 播放控件盒子 -->
  <div
    class="audio-play-wrap"
    @select.prevent
    @mouseover="mouseOverHandle($event)"
    @mouseout="mouseOutHandle($event)"
    ref="audioPlayRef"
  >
    <!-- 锁定盒子 -->
    <div class="upon">
      <div class="left f-fl playbar">
        <a
          href="javascript:void(0);"
          class="btn playbar"
          :class="playerSetting.lock ? 'lock' : 'unlock'"
          @click="playerSetting.lock = !playerSetting.lock"
        ></a>
      </div>
      <div class="right f-fl playbar"></div>
    </div>
    <div class="bg playbar"></div>
    <!-- 控件 -->
    <div class="audioplay" ref="audiomainRef">
      <!-- 切换和播放音乐 -->
      <div class="btns">
        <a href="javascript:void(0);" class="pre icn" @click="preSong"></a
        ><a href="javascript:void(0);" class="ply icn" @click="PlayClick" ref="plyicnRef"></a
        ><a href="javascript:void(0);" class="nxt icn" @click="nxtSong"></a>
      </div>
      <!-- 音乐图片 -->
      <div class="head">
        <template v-if="JSON.stringify(currentSong) !== '{}'">
          <img :src="currentSong.al.picUrl + '?param=34y34'" alt="" />
          <router-link :to="'/song?id=' + currentSong.id" href="" class="msk icn"></router-link>
        </template>
        <!-- v-if="!currentSong.al.picUrl" -->
        <template v-else>
          <img src="https://s4.music.126.net/style/web2/img/default/default_album.jpg" alt="" /><a
            href="javascript:void(0);"
            class="msk icn"
          ></a>
        </template>
      </div>
      <!-- 播放详情 -->
      <div class="play" ref="playwrapRef">
        <!-- 歌曲详情 -->
        <div class="words">
          <router-link :to="'/song?id=' + currentSong.id" class="song">{{
            currentSong.name
          }}</router-link>
          <span class="singer f-thide clearfix f-fl">
            <router-link
              class="art-name"
              :to="'/artist?id=' + item.id"
              v-for="(item, i) in currentSong.ar"
              :key="(i + 1) * 10086"
              >{{ currentSong.ar.length - 1 == i ? item.name : item.name + '/' }}</router-link
            ></span
          ><router-link to="" class="src"></router-link>
        </div>
        <!-- 播放进度 -->
        <div class="m-pbar">
          <div class="barbg">
            <div class="rdy" @click="curClick($event)" ref="rdyRef"></div>
            <div
              class="cur"
              :style="{ width: (curwidth > 100 ? 100 : curwidth) + '%' }"
              @click="curClick($event)"
            >
              <span class="btn" @mousedown="btnMousedown"><i></i></span>
            </div>
            <span class="time"
              ><em>{{ currentTimeFormat }}</em
              >/ {{ (duration * 1000) | songDuration }}</span
            >
          </div>
        </div>
      </div>
      <!-- 收藏、分享 -->
      <div class="oper">
        <a
          href="javascript:void(0);"
          class="icn icn-pip"
          @click="$Message({ msg: '功能暂未开发！！！' })"
        ></a
        ><a href="javascript:void(0);" class="icn icn-like" @click="operationClick"></a
        ><a href="javascript:void(0);" class="icn icn-share" @click="operationClick"></a>
      </div>
      <!-- 歌曲列表、音量、播放模式 -->
      <div class="ctrl">
        <div class="volume-wrap" ref="volWrapRef" v-show="volumeDisplay">
          <div class="barbg playbar"></div>
          <div class="vbg">
            <div
              class="curr playbar"
              ref="volCurrRef"
              :style="{ height: playerSetting.volume * 81 + 'px' }"
            ></div>
            <div
              class="btn u-iconall"
              ref="volbtnRef"
              @mousedown="changeVolume($event)"
              :style="{ top: (1 - playerSetting.volume) * 81 + 'px' }"
            ></div>
          </div>
        </div>
        <!-- mode 2 one 4 loop 5 shuffle -->
        <a
          href="javascript:void(0);"
          class="icn"
          :class="playerSetting.volume === 0 ? 'icn-volno' : 'icn-vol'"
          @click="volumeDisplay = !volumeDisplay"
        ></a
        ><a
          href="javascript:void(0);"
          class="icn"
          :class="
            playerSetting.mode == 2
              ? 'icn-one'
              : playerSetting.mode == 4
              ? 'icn-loop'
              : 'icn-shuffle'
          "
          :title="playerSetting.mode == 2 ? '单曲循环' : playerSetting.mode == 4 ? '循环' : '随机'"
          @click="changeMode"
        ></a>
        <span class="add f-pr">
          <span>已开始播放</span>
          <a
            href="javascript:void(0);"
            class="icn icn-list"
            @click="$store.commit('Music/setListDisplay', !listDisplay)"
            >{{ this.songList.length }}</a
          >
        </span>
      </div>
      <AudioPlayList v-show="listDisplay" ref="AudioPlayListRef"></AudioPlayList>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { SongDetail } from '@/api/song.js'
import { songDuration } from '@/utils/filters.js'
import { operationClick } from '@/utils/methods.js'
import AudioPlayList from './AudioPlayList/AudioPlayList.vue'
export default {
  components: { AudioPlayList },
  data() {
    return {
      // 音乐地址
      src: 'https://music.163.com/song/media/outer/url?id=',
      // 是否暂停
      paused: true,
      // 音频
      audio: null,
      // 当前时长
      currentTime: 0,
      // 歌曲详情
      songDetail: { al: { picUrl: '' }, name: '' },
      // 总时长
      duration: 0,
      // 定时器歌曲现在时长
      timer: null,
      playTimer: null,
      // 时长宽度
      curwidth: 0,
      // 进度条小圆点是否被点击
      btnIsClick: false,
      // 播放模式列表
      modeList: [2, 4, 5],
      // 音量控件显示
      volumeDisplay: false
    }
  },
  methods: {
    // 获取歌曲详情
    async getSongDetail() {
      if (!this.songList.length) {
        return
      }
      if (!this.songList[this.playerSetting.index]) {
        await this.$store.commit('Music/setplayerSettingIndex', 0)
        console.log(this.playerSetting.index)
      }
      const ids = this.songList[this.playerSetting.index].id
      const { data } = await SongDetail(ids)
      this.songDetail = data.songs[0]
      this.duration = this.songDetail.dt / 1000
      console.log(data)
    },
    // 开启定时器，记录歌曲播放进度
    setInter() {
      console.log(this.paused)
      if (this.paused) {
        clearInterval(this.timer)
        clearInterval(this.$refs.AudioPlayListRef.timerLyc)
        this.timer = null
        this.$refs.AudioPlayListRef.timerLyc = null
      } else {
        // 歌词显示
        // console.log(this.$refs.AudioPlayListRef, '11111')
        this.$refs.AudioPlayListRef.setLycInter()
        this.timer = setInterval(() => {
          this.currentTime = this.audio.currentTime
          // 进度条长度
          this.curwidth = (this.currentTime / this.duration) * 100
        }, 100)
      }
    },
    // 播放暂停
    Play() {
      // 防止多次触发
      if (this.playTimer) {
        return
      } else {
        this.playTimer = setTimeout(() => {
          clearTimeout(this.playTimer)
          this.playTimer = null
        }, 200)
      }
      // this.getSongUrl()
      if (!this.audio) {
        this.audio = new Audio(this.src + this.currentSong.id + '.mp3')
      } else {
        const tempsrc = this.src + this.currentSong.id + '.mp3'
        if (this.audio.src !== tempsrc) {
          this.audio.pause()
          clearInterval(this.timer)
          clearInterval(this.$refs.AudioPlayListRef.timerLyc)
          this.$refs.AudioPlayListRef.timerLyc = null
          this.paused = true
          this.curwidth = 0
          this.audio = new Audio(tempsrc)
        }
      }
      console.log(this.audio)
      // this.duration = this.audio.duration
      console.log(this.paused)
      if (this.paused) {
        this.audio.play()
        this.audio.volume = this.playerSetting.volume
        this.$refs.plyicnRef.classList.add('pau')
      } else {
        this.audio.pause()
        this.$refs.plyicnRef.classList.remove('pau')
      }
      this.paused = !this.paused
      console.log('playinter')
      this.setInter()
      // 更换图标
      // this.$refs.plyicnRef.classList.toggle('pau')

      // console.log(this.currentTime)
    },
    PlayClick() {
      if (!this.songList.length) {
        if (this.audio) {
          if (this.paused) {
            this.audio.play()
            this.audio.volume = this.playerSetting.volume
            this.$refs.plyicnRef.classList.add('pau')
          } else {
            this.audio.pause()
            this.$refs.plyicnRef.classList.remove('pau')
          }
          this.paused = !this.paused
          console.log('songList0-playinter')
          this.setInter()
        }
        return
      }
      this.Play()
    },
    // 上一首歌
    preSong() {
      let index = 0
      if (!this.songList.length) return
      if (this.playerSetting.mode === 5) {
        index = Math.ceil(Math.random() * (this.songList.length - 1))
      } else {
        index =
          this.playerSetting.index - 1 < 0 ? this.songList.length - 1 : this.playerSetting.index - 1
      }
      this.$store.commit('Music/setplayerSettingIndex', index)
      // this.Play()
    },
    // 下一首歌
    nxtSong() {
      let index = 0
      if (!this.songList.length) return
      if (this.playerSetting.mode === 5) {
        index = Math.ceil(Math.random() * (this.songList.length - 1))
      } else {
        index =
          this.playerSetting.index + 1 >= this.songList.length ? 0 : this.playerSetting.index + 1
      }
      console.log('index', index)
      console.log('playerSetting.index', this.playerSetting.index)
      console.log('this.songList.length', this.songList.length)
      this.$store.commit('Music/setplayerSettingIndex', index)
      // this.Play()
    },
    // 监听鼠标在进度条中的移动
    rdyMove(e) {
      const left = this.$refs.audiomainRef.offsetLeft + this.$refs.playwrapRef.offsetLeft
      let tempWidth = ((e.clientX - left) / 466) * 100
      tempWidth = tempWidth < 0 ? 0 : tempWidth > 100 ? 100 : tempWidth
      console.log(tempWidth)
      this.curwidth = tempWidth
      this.currentTime =
        (this.curwidth / 100) * this.duration > this.duration
          ? this.duration
          : (this.curwidth / 100) * this.duration
    },
    // 进度条按钮鼠标按下
    btnMousedown() {
      this.btnIsClick = true
      clearInterval(this.timer)
      clearInterval(this.$refs.AudioPlayListRef.timerLyc)
      this.timer = null
      this.$refs.AudioPlayListRef.timerLyc = null
      this.$refs.audioPlayRef.addEventListener('mousemove', this.rdyMove)
      this.$refs.audioPlayRef.addEventListener('mouseleave', () => {
        this.$refs.audioPlayRef.removeEventListener('mousemove', this.rdyMove)
      })
      this.$refs.audioPlayRef.addEventListener('mouseup', () => {
        if (this.btnIsClick) {
          this.$refs.audioPlayRef.removeEventListener('mousemove', this.rdyMove)
          console.log(this.paused)
          if (this.paused) {
            clearInterval(this.timer)
            clearInterval(this.$refs.AudioPlayListRef.timerLyc)
            this.timer = null
            this.$refs.AudioPlayListRef.timerLyc = null
          } else {
            console.log('mouseupinter')
            this.setInter()
          }
          this.btnIsClick = false
        }
      })
    },
    // 进度条按钮鼠标松开
    btnMouseup() {
      this.btnIsClick = false
    },
    curClick(e) {
      // console.log(e)
      // console.log(e.clientX)
      // console.log(e.clientX - 455)
      const left = this.$refs.audiomainRef.offsetLeft + this.$refs.playwrapRef.offsetLeft
      this.curwidth =
        ((e.clientX - left) / 466) * 100 > 100 ? 100 : ((e.clientX - left) / 466) * 100
      if (!this.audio) {
        this.audio = new Audio(this.src)
      }
      this.audio.currentTime = (this.curwidth / 100) * this.duration
      // console.log((this.curwidth / 100) * this.audio.duration)
      // this.audio.fastSeek((this.curwidth / 100) * this.audio.duration)
      // console.log(this.audio.currentTime)
      this.currentTime = (this.curwidth / 100) * this.duration
    },
    mouseOverHandle(e) {
      e.currentTarget.style.bottom = '0'
    },
    mouseOutHandle(e) {
      if (this.listDisplay) {
        return
      }
      if (!this.playerSetting.lock) {
        e.currentTarget.style.bottom = '-46px'
      }
    },
    // 改变播放模式
    changeMode() {
      for (let i = 0; i < this.modeList.length; i++) {
        if (this.modeList[i] === this.playerSetting.mode) {
          if (i === this.modeList.length - 1) {
            this.$store.commit('Music/setplayerSettingMode', this.modeList[0])
          } else {
            this.$store.commit('Music/setplayerSettingMode', this.modeList[i + 1])
          }
          break
        }
      }
    },
    // 改变音量
    changeVolume(event) {
      const initY = event.clientY
      const initTop = this.$refs.volbtnRef.offsetTop
      const initHeight = this.$refs.volCurrRef.offsetHeight
      let volume = 0
      const vm = this
      function volMouseMove(e) {
        let y = initY - e.clientY
        if (y < initTop - 81) {
          y = initTop - 81
        } else if (y > initTop) {
          y = initTop
        }
        vm.$refs.volbtnRef.style.top = initTop - y + 'px'
        vm.$refs.volCurrRef.style.height = initHeight + y + 'px'
        volume = (initHeight + y) / 81
        // 动态调节音乐音量
        if (vm.audio) {
          vm.audio.volume = volume
        }
        // vm.$store.commit('setplayerSettingVol', (initHeight + y) / 81)
      }
      this.$refs.volWrapRef.addEventListener('mousemove', volMouseMove)
      this.$refs.volWrapRef.addEventListener('mouseup', () => {
        this.$store.commit('Music/setplayerSettingVol', volume)
        this.$refs.volWrapRef.removeEventListener('mousemove', volMouseMove)
      })
      this.$refs.volWrapRef.addEventListener('mouseleave', () => {
        this.$store.commit('Music/setplayerSettingVol', volume)
        this.$refs.volWrapRef.removeEventListener('mousemove', volMouseMove)
      })
    },
    // 收藏、分享
    operationClick
  },
  computed: {
    ...mapState({
      playerSetting: state => state.Music.playerSetting,
      songList: state => state.Music.songList,
      listDisplay: state => state.Music.listDisplay,
      currentSong: state => state.Music.currentSong,
      isLogin: state => state.Login.isLogin
    }),
    currentTimeFormat() {
      if (this.currentTime > this.duration) {
      }
      const m = parseInt(this.currentTime / 60)
      const s = parseInt(this.currentTime % 60)
      return s || m ? m.toString().padStart(2, '0') + ':' + s.toString().padStart(2, '0') : '00:00'
    }
  },
  watch: {
    curwidth(val) {
      // 监听时长宽度，放完自动切换下一首
      if (Math.floor(val) === 100) {
        if (!this.songList.length) {
          this.audio.currentTime = 0
          this.audio.pause()
          this.paused = true
          this.$refs.plyicnRef.classList.remove('pau')
          return
        }
        // 判断是否是单曲循环
        if (this.playerSetting.mode === 2) {
          this.audio.currentTime = 0
          this.audio.play()
        } else {
          this.nxtSong()
        }
      }
    },
    songList: {
      handler(val) {
        // this.playerSetting.index = 0
        if (val.length === 0) {
          return
        }
        // console.log('test1222',this.$store.state.Music.isPlay)
        // 判断是否在初始化，如果是刷新页面就不自动播放
        if (this.$store.state.Music.isPlay && !this.$store.state.Music.indexChanging) {
          // if (this.$store.state.Music.isPlay) {
          this.Play()
          console.log('songlist play')
          this.$refs.AudioPlayListRef.getLyric()
          this.getSongDetail()
        }
      },
      deep: true
    },
    'playerSetting.index'() {
      if (!this.songList.length) return
      this.$store.commit('Music/setIndexChanging', true)
      console.log('play前', this.$store.state.Music.isPlay)
      if (this.$store.state.Music.isPlay) {
        this.Play()
        console.log('index play')
        this.getSongDetail()
        this.$refs.AudioPlayListRef.getLyric()
      }
      setTimeout(() => {
        this.$store.commit('Music/setIndexChanging', false)
      }, 100)
    }
  },
  filters: {
    songDuration
  },
  created() {
    this.paused = true
    // 初始化播放控件设置
    console.log('初始化设置前', this.$store.state.Music.isPlay)
    this.$store.commit('Music/initPlayerSetting')
    console.log('初始化设置后', this.$store.state.Music.isPlay)
    // 设置控件是否显示
    setTimeout(() => {
      if (this.playerSetting.lock) {
        this.$refs.audioPlayRef.style.bottom = '0'
      } else {
        this.$refs.audioPlayRef.style.bottom = '-46px'
      }
    }, 300)
    // 初始化播放列表
    console.log('初始化列表前', this.$store.state.Music.isPlay)
    this.$store.commit('Music/initSongList')
    this.$store.dispatch('Music/changeIsInitSongList')
    // console.log('初始化列表后', this.$store.state.isInitSongListing)
    if (this.songList.length !== 0) {
      // 获取歌词
      // this.getLyric()
      // 获取歌曲详情
      this.getSongDetail()
    }
  }
}
</script>

<style lang="less" scoped>
@import './AudioPlayer.less';
</style>
